function WSSHClient() {
};

WSSHClient.prototype._generateEndpoint = function () {
    var protocol = 'ws://';
    if (window.location.protocol === 'https:') {
        protocol = 'wss://';
    }
    var endpoint = protocol + window.location.host + window.getContextPath() +"/"+ window.localStorage.getItem("ws_uri")
    ;
    return endpoint;
};

WSSHClient.prototype.connect = function (options) {
    var endpoint = this._generateEndpoint();

    if (window.WebSocket) {
        //如果支持websocket
        this._connection = new WebSocket(endpoint);
    } else {
        //否则报错
        options.onError('WebSocket Not Supported');
        return;
    }

    this._connection.onopen = function () {
        options.onConnect();
        //开始连接，启动心跳检查
        heartCheck.start();
    };

    this._connection.onmessage = function (evt) {
        var data = evt.data.toString();
        //如果是返回心跳，不执行onData();方法
        if (data !== "Heartbeat healthy") {
            options.onData(data);
        } else {
            //心跳健康，重置重连次数
            reconnectTimes = 0;
        }
        //收到消息，重置心跳检查
        heartCheck.start();
    };


    this._connection.onclose = function (evt) {
        options.onClose();
        reconnect(options);
    };
};

WSSHClient.prototype.send = function (data) {
    this._connection.send(JSON.stringify(data));
};

WSSHClient.prototype.sendInitData = function (options) {
    //连接参数
    this._connection.send(JSON.stringify(options));
};

WSSHClient.prototype.sendClientData = function (data) {
    var window_width = $(window).width();
    var window_height = $(window).height();
    var cols = Math.floor(window_width/9);
    var rows = Math.floor(window_height/20);
    //发送指令
    this._connection.send(JSON.stringify({"operate": "command", "command": data, "cols": cols , "rows": rows , "width": window_width , "height":  window_height}))
};
var client = new WSSHClient();
window.addEventListener('resize', ()=>{
    if (window.fitAddon){
        window.fitAddon.fit();
    }
});
var heartCheck = {
    checkTimeout: 5000,//心跳检查时间
    closeTimeout: 2000,//无心跳超时时间
    checkTimeoutObj: null,//心跳检查定时器
    closeTimeoutObj: null,//无心跳关闭定时器
    start: function () {
        //清除定时器
        clearTimeout(this.checkTimeoutObj);
        clearTimeout(this.closeTimeoutObj);

        // console.log("检查心跳");
        var _this = this;

        this.checkTimeoutObj = setTimeout(function () {
            client.send({operate: "heartbeat"});
            _this.closeTimeoutObj = setTimeout(function () {
                console.log("无心跳，关闭连接");
                client.close();
            }, _this.closeTimeout);
        }, this.checkTimeout);
    }
}

//重新连接
var lockReconnect = false;//重连锁，避免重复连接
var reconnectTimes = 0;
var maxReconnectTimes = 6;
var resetReconnectTimeout;
function reconnect(options) {
    if (lockReconnect)
        return;

    // console.log("重新连接");
    clearTimeout(resetReconnectTimeout);

    //超过次数不重启
    if (reconnectTimes >= maxReconnectTimes) {
        options.onOverReconnect(reconnectTimes);
        return;
    }

    options.onReconnect(++reconnectTimes);

    setTimeout(function() {
        client.connect(options);
        lockReconnect = false;
    }, 500);

    //3分钟没重连，设为0次
    resetReconnectTimeout = setTimeout(function() {
        reconnectTimes=0;
    }, 3*60*1000);
}
/*
 * {
    operate:'connect',
    wsUrl:'webssh',
    host: '',//IP
    port: '22',//端口号
    username: '',//用户名
    password: ''//密码
}*/
function openTerminal(options){
    var window_width = $(window).width();
    var window_height = $(window).height();
    var term= window.term = new Terminal({
        cols: Math.floor(window_width/9),
        rows: Math.floor(window_height/20),
        useStyle:true,
        cursorBlink: true, // 光标闪烁
        cursorStyle: "block", // 光标样式  null | 'block' | 'underline' | 'bar'
        scrollback: 10000, //回滚
        tabStopWidth: 8, //制表宽度
        screenKeys: true
    });
    var fitAddon=window.fitAddon = new FitAddon.FitAddon();
    term.loadAddon(fitAddon);

    term.onData(data => {
        //键盘输入时的回调函数
        client.sendClientData(data);
    });
    term.open(document.getElementById('terminal-container'));
    fitAddon.fit();
    term.focus();
    //在页面上显示连接中...
    term.write('Connecting...\r\n');
    //执行连接操作
    client.connect({
        onError: function (error) {
            //连接失败回调
            term.write('Error: ' + error + '\r\n');
        },
        onConnect: function () {
            //连接成功回调
            term.write('onConnect...\r\n');
            client.sendInitData(options);
            term.onResize(data=>{
                client.send({
                    "operate": "command"
                    , "command": ''
                    , "cols": data.cols
                    , "rows": data.rows
                    , "width": $("#terminal-container").width()
                    , "height": $("#terminal-container").height()
                });
            });
        },
        onClose: function () {
            //连接关闭回调
            term.write("\rconnection closed");
            window.location.href=window.getContextPath()+"/login";
        },
        onData: function (data) {
            //收到数据时回调
            term.write(data);
        }
    });
}
